package luz.javaproxy.plugins.ProxySelector;


import java.util.List;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;

import luz.javaproxy.common.Tuple;

public class ProxySelectorTable extends JTable{
	private static final long serialVersionUID = 534648762781480107L;
	private final MyTableModel model;
	private ActiveProxyListener activeProxyListener;
	
	public ProxySelectorTable(){
		super();
		
		model=new MyTableModel();
		this.setModel(model);
		this.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		
		this.getColumnModel().getColumn(1).setMinWidth(50);
		this.getColumnModel().getColumn(1).setMaxWidth(50);
	}
	
	public void setProxies(List<Tuple<String,Boolean>> proxies){
		model.setProxies(proxies);
	}
	
	public void updateTable(){
		model.fireTableDataChanged();
	}
	
	public void updateRow(int row){
		model.fireTableRowsUpdated(row, row);
	}
	
	public void setActiveProxyListener(ActiveProxyListener activeProxyListener){
		this.activeProxyListener=activeProxyListener;
	}
	
	public interface ActiveProxyListener {
		public void proxyChanged(int row, boolean selected);
	}
	
	private class MyTableModel extends AbstractTableModel {
		private static final long serialVersionUID = 7780019195084742274L;
		private String[] columnNames = {"Proxy", "Selected"};
	    private List<Tuple<String,Boolean>> proxies;
	    

		public void setProxies(List<Tuple<String,Boolean>> proxies){
			this.proxies=proxies;
			fireTableDataChanged();
		}
		
		@Override
	    public int getColumnCount() {
	        return columnNames.length;
	    }
	    
	    @Override
	    public int getRowCount() {
	        return proxies.size();
	    }
	    
	    @Override
	    public String getColumnName(int col) {
	        return columnNames[col];
	    }
	    
	    @Override
	    public Object getValueAt(int row, int col) {
	    	switch (col){
	    		case 0:
	    			return proxies.get(row).getFirst();
	    		case 1: 
	    			return proxies.get(row).getSecond();
	    		default: return null;
	    	}
	    }
	    
		@Override
	    @SuppressWarnings("unchecked")
	    public Class getColumnClass(int c) {
	    	Object r = getValueAt(0, c);
	        return r!=null?r.getClass():Object.class;
	    }
	    
	    @Override
	    public boolean isCellEditable(int row, int col) {
	    	return (col==1);
        }
	    
	    @Override
        public void setValueAt(Object value, int row, int col) {
			activeProxyListener.proxyChanged(row, (Boolean)value);
        }
	}





	
}
